package vumt.radiocountries.util;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import vumt.radiocountries.object.ChannelObject;
import vumt.radiocountries.object.SubChannelObject;

public class ChannelHandler extends DefaultHandler {
	Boolean currentElement = false;
	String currentValue = "";
	ChannelObject channel = null;
	SubChannelObject subChannel = null;
	private ArrayList<ChannelObject> channelList = new ArrayList<ChannelObject>();
	private ArrayList<SubChannelObject> listSubChannel = null;
	private ArrayList<String> listLink = null;

	public ArrayList<ChannelObject> getChannelList() {
		return this.channelList;
	}

	// Called when tag starts
	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		currentElement = true;
		currentValue = "";
		if (localName.equals(Global.CHANNEL)) {
			channel = new ChannelObject();
			listSubChannel = new ArrayList<SubChannelObject>();
		}
		if (localName.equals(Global.NAME)) {
			subChannel = new SubChannelObject();
			listLink = new ArrayList<String>();
		}
	}

	// Called when tag closing
	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		currentElement = false;
		// Set values for channel
		if (localName.equalsIgnoreCase(Global.COUNTRY))
			channel.setCountry(currentValue);
		else if (localName.equalsIgnoreCase(Global.FLAG))
			channel.setFlag(currentValue);
		else if (localName.equalsIgnoreCase(Global.WEB)) {
			subChannel.setWebsite(currentValue);
			subChannel.setListLink(listLink);
			listSubChannel.add(subChannel);
		}
		else if (localName.equalsIgnoreCase(Global.NAME))
			subChannel.setName(currentValue);
		else if (localName.equalsIgnoreCase(Global.LINK)) 
			listLink.add(currentValue);
		else if (localName.equalsIgnoreCase(Global.CHANNEL)) {
			channel.setListSubChannel(listSubChannel);
			channelList.add(channel);
		}
	}

	// Called to get tag characters
	@Override
	public void characters(char ch[], int start, int length)
			throws SAXException {
		if (currentElement)
			currentValue = currentValue + new String(ch, start, length);
	}
}
